// pages/contactMessage/contactMessage.js
const app = getApp()
import {baseUrl} from "../../utils/api.js";

var utils = require('../../utils/util.js');
const {
  getTimeSeconds
} = utils
const recorderManager = wx.getRecorderManager();
const audioCtx = wx.createInnerAudioContext('myAudio')
const innerAudioContext = wx.createInnerAudioContext()
innerAudioContext.autoplay = false

Page({
  /**
   * 页面的初始数据
   */
  data: {
    newslist: [],
    newsinfo: [],
    userInfo: {},
    scrollTop: 0,
    increase: false, //图片添加区域隐藏
    aniStyle: true, //动画效果
    previewImgList: [],
    message: "",
    mic_audio: false,
    audio_mic: false,
    isaudio: true,
    audio_text: "按住 说话",
    setInter: '',
    toView: '',
    scrollHeight: '100vh',
    userId: '',
    on_line_uid: '',
    isSend: true,
    socketOpen: false,
    socketMsgQueue: []
  },
  copyToCli: function (e) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.message,
      success(res) {
        app.showTipMsg('复制成功')
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '获取数据中',
    })
    var that = this
    var date = new Date();
    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    
    console.log('options.userid:', options.userid);
    console.log('options.id:', app.globalData.userInfo.id);
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo
      })
    }
    that.setData({
      userId: options.userid
    })
    console.log('options.userid:', that.data.userId);
    let url = '/chat_api/detail';
    let params = {
      tuid: options.userid,
      uid: app.globalData.userInfo.id,
    }
    app.HttpPostSend(url, params, function (res) {
      wx.hideLoading();
      if (res.msg != "success") {
        app.showTipMsg(res.msg);
      } else {
        var list = [];
        var info = [];
        if (res.data) {
          list = res.data.lists;
          info = res.data.info;
          for (var i = 0; i < list.length; i++) {
            list[i].showTime = false;
            if ((Number(timestamp) - Number(list[i].create_time)) > 1800) {
              list[i].showTime = true;
            } else {
              // list[i].showTime = false;
            }

            var ii = parseInt(i) - 1;
            if (i < list.length - 1 && i > 0) {
              if ((Number(list[i].create_time) - Number(list[ii].create_time)) < 1800) {
                list[i].showTime = false;
              } else {
                list[i].showTime = true;
              }
            }
            if (i == list.length - 1 && i > 0) {
              var iii = parseInt(i) - 1;
              if ((Number(list[i].create_time) - Number(list[iii].create_time)) < 1800) {
                list[i].showTime = false;
              } else {
                list[i].showTime = true;
              }
            }


          }
          for (var i = 0; i < list.length; i++) {
            if (list[i].type == 3) {
              list[i].isaudio = true;
              list[i].noPlay = true;
              if (!!list[i].length) {

                if (list[i].length > 3) {
                  list[i].changeWidth = 'width:' + Number((list[i].length - 3) * 2 + 60) + 'px';
                } else {
                  list[i].changeWidth = 'width:60px';
                }
              } else {
                list[i].length = '';
                list[i].changeWidth = 'width:60px';
              }
            }

            list[i].create_time = that.timestampToTime(list[i].create_time * 1000);
          }
          console.log(list);
          that.setData({
            newslist: list,
            newsinfo: info,
          })
          that.setData({
            toView: 'msg-' + (that.data.newslist.length - 1)
          })
        }
      }
    });
  },
  wssInit: function () {
    var that = this;
    this.connectWss();
    wx.onSocketClose(function () {
      console.log("居然关闭了");
      that.connectWss();
    })
    // 链接失败显示
    wx.onSocketError(function (res) {
      console.log('WebSocket连接打开失败，请检查！', res);
      that.setData({
        isOpen: false,
        statusMsg: '已断开'
      });
      that.connectWss();
    });
    // 监听连接成功
    wx.onSocketOpen(function (res) {
      console.log('WebSocket连接已打开！')

      that.setData({
        isOpen: true,
        statusMsg: '已连接'
      });
      wx.sendSocketMessage({
        data: JSON.stringify({ message: '', uid: app.globalData.userInfo.id, tuid: 0, p_id: 0, type: 1, is_read: 2, length: '' }),
        success: res => {

        }
      });
      // that.send(0)
      wx.onSocketMessage(function (res) {

        
        var re_data1 = res.data;
        var re_data = JSON.parse(re_data1); //可用此方法来转换
        if (re_data.status>0){

          if (Number(re_data.on_line_uid) != Number(app.globalData.userInfo.id)) {
            // 发送模板消息-未读回信提醒
            app.sendTemplateMessage(that.data.userId, 3, '/pages/socks/socks?jsid=' + that.data.userId + '&fsid=' + app.globalData.userInfo.id, '', '', '', '')
            
          }


          var message_list = re_data.message;
          var list = [];
          var nlist = [];
          list = that.data.newslist;
          nlist = message_list;

          console.log(nlist);
          var room_id='';
          var room_id2 = '';
          room_id = app.globalData.userInfo.id + '/' + that.data.userId;
          room_id2 = that.data.userId + '/' + app.globalData.userInfo.id;
          console.log(room_id);
          console.log(room_id2);
          if (nlist.room_id == room_id || nlist.room_id == room_id2) {
            if (nlist != '') {
              nlist.showTime = false;

              if (nlist.type == 3) {
                nlist.isaudio = true;
                nlist.noPlay = true;
                if (!!nlist.length) {

                  if (nlist.length > 3) {
                    nlist.changeWidth = 'width:' + Number((nlist.length - 3) * 2 + 60) + 'px';
                  } else {
                    nlist.changeWidth = 'width:60px';
                  }
                } else {
                  nlist.length = '';
                  nlist.changeWidth = 'width:60px';
                }
              }

              var lst = list.length - 1;
              var d1 = list[lst].create_time;
              d1 = d1.substring(0, 19);
              d1 = d1.replace(/-/g, '/');
              var timestamp1 = new Date(d1).getTime();

              var d2 = nlist.create_time;
              d2 = d2.substring(0, 19);
              d2 = d2.replace(/-/g, '/');
              var timestamp2 = new Date(d2).getTime();
              console.log(timestamp1);
              console.log(timestamp2);
              console.log((Number(timestamp2) - Number(timestamp1)));
              if ((Number(timestamp2) - Number(timestamp1)) < 3600000) {
                nlist.showTime = false;
              } else {
                nlist.showTime = true;
              }
              // nlist.create_time = that.timestampToTime(nlist.create_time * 1000);

              list.push(nlist);
              console.log(list);
              that.setData({
                newslist: list
                
              })

              that.setData({
                toView: 'msg-' + (that.data.newslist.length - 1)
              })
            } else {

              that.setData({
                newslist: list
              })
            }
          }

        }else{
          app.showTipMsg(re_data.msg);
        }
      });
      // wx.sendSocketMessage({

      // });
    })
  },
  // 向服务器发送消息
  send: function (state) {
    var that = this;
    // console.log('尝试向服务器发送消息：');
    // that.connectWss()
    if (that.data.message.trim() == '' && state!=0) {
      that.setData({
        increase: false
      })
      wx.showToast({
        title: '内容不能为空！',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    
    // that.getOnLine();
    wx.sendSocketMessage({
      data: JSON.stringify({message: that.data.message,uid: app.globalData.userInfo.id,tuid: that.data.userId,p_id: that.data.newslist[0].id,type: 1,is_read: 2,length:''}),
      success: res => {
        that.setData({
          message: '',
          increase: false
        })


      }, 
      fail: res => {
        wx.showModal({
          title: '提示',
          content: '服务忙，请重新发送',
          showCancel: false,
          success: function () {
            that.wssconnect();
          }
        })

      },
    });
  },
  connectWss: function () {
    this.setData({
      statusMsg: '连接中。。。'
    });
    this.wssconnect();
  },
  wssconnect: function () {
    //Socket连接
    var sk = wx.connectSocket({
      url: 'wss://wssai.51jlkj.com/server/index/index'
    })
    this.setData({sk:sk});

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    var that = this
    that.wssInit()
    let url2 = '/user_api/onLine';
    let params2 = {
      uid: app.globalData.userInfo.id,
      on_line_uid: that.data.userId
    }
    app.HttpPostSend(url2, params2, function (res) {

    });

    //每隔五秒获取列表数据
    // that.data.setInter = setInterval(function () {
    //   //循环执行代码
    //   let url = '/chat_api/ajax';
    //   let params = {
    //     id: that.data.newslist[0].id,
    //     last_id: that.data.newslist[that.data.newslist.length - 1].id,
    //     uid: app.globalData.userInfo.id
    //   }
    //   app.HttpPostSend(url, params, function (res) {
    //     if (res.msg != "success") {
    //       app.showTipMsg(res.msg);
    //     } else {
    //       var list = [];
    //       var nlist = [];
    //       list = that.data.newslist;
    //       nlist = res.data;

    //       if (res.data.length > 0) {
    //         for (var i = 0; i < nlist.length; i++) {
    //           nlist[i].showTime = false;

    //           if (nlist[i].type == 3) {
    //             nlist[i].isaudio = true;
    //             nlist[i].noPlay = true;
    //             if (!!nlist[i].length) {

    //               if (nlist[i].length > 3) {
    //                 nlist[i].changeWidth = 'width:' + Number((nlist[i].length - 3) * 2 + 60) + 'px';
    //               } else {
    //                 nlist[i].changeWidth = 'width:60px';
    //               }
    //             } else {
    //               nlist[i].length = '';
    //               nlist[i].changeWidth = 'width:60px';
    //             }
    //           }
    //           list.push(nlist[i]);
    //         }
    //         that.setData({
    //           newslist: list
    //         })
    //         that.setData({
    //           toView: 'msg-' + (that.data.newslist.length - 1)
    //         })
    //       } else {
    //         that.setData({
    //           newslist: list
    //         })
    //       }
    //     }
    //   });
    // }, 2000) //循环时间 这里是1秒
  },
  // 页面卸载
  onUnload() {

    var that = this
    that.data.sk.close();
    wx.onSocketClose(function(){
      console.log('Socket关闭。。');
      clearInterval(that.data.setInter);
      // let url = '/chat_api/is_read';
      // let params = {
      //   id: that.data.newslist[that.data.newslist.length - 1].id,
      //   uid: app.globalData.userInfo.id
      // }
      // app.HttpPostSend(url, params, function (res) {

      // });

      let url2 = '/user_api/onLine';
      let params2 = {
        uid: app.globalData.userInfo.id,
        on_line_uid: 0
      }
      app.HttpPostSend(url2, params2, function (res) {

      });
    });
    


  },
  timestampToTime: function (timestamp) {
    var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '/';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '/';
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate() + "";
    var h = date.getHours() + ':';
    var m = date.getMinutes();
    if (String(m).length == 1) {
      m = "0" + m;
    }
    var s = date.getSeconds();
    return Y + M + D + " " + h + m;
  },//转化后格式xxxx-xx-xx,

  //获取对象是否在线
  getOnLine: function () {
    var that = this
    let url3 = '/user_api/getUserInfos';
    let params3 = {
      uid: that.data.userId
    }
    app.HttpPostSend(url3, params3, function (res) {
      if (res.msg != "success") {
        app.showTipMsg(res.msg);
      } else {
        that.setData({
          on_line_uid: res.data.on_line_uid
        })
      }
    });
  },

  //事件处理函数
  // send: function () {
  // var that = this
  // if (that.data.message == "") {
  //   wx.showToast({
  //     title: '消息不能为空哦~',
  //     icon: "none",
  //     duration: 2000
  //   })
  // } else {
  //   that.sendSocketMessage(that.data.message);
  //   wx.onSocketMessage(function (res) {
  //     console.log('收到服务器内容：' + res.data)
  //   })
  //   return false;
  //   setTimeout(function () {
  //     that.setData({
  //       increase: false
  //     })
  //   }, 500)
  //   that.getOnLine();

  //   let url = '/chat_api/addInfo';
  //   let params = {
  //     uid: app.globalData.userInfo.id,
  //     a_uid: that.data.userId,
  //     message: that.data.message,
  //     p_id: that.data.newslist[0].id,
  //     type: 1,
  //     is_read: 2
  //   }
  //   that.setData({
  //     message: ""
  //   })
  //   app.HttpPostSend(url, params, function (res) {
  //     if (Number(that.data.on_line_uid) != Number(app.globalData.userInfo.id)) {
  //       // 发送模板消息-未读回信提醒
  //       app.sendTemplateMessage(that.data.userId, 3, '/pages/socks/socks?jsid=' + that.data.userId + '&fsid=' + app.globalData.userInfo.id, '', '', '', '')
  //     }
  //   });
  // }
  // },

  //监听input值的改变
  bindChange(res) {
    this.setData({
      message: res.detail.value
    })
  },
  cleanInput() {
    //button会自动清空，所以不能再次清空而是应该给他设置目前的input值
    this.setData({
      message: this.data.message
    })
  },
  increase() {
    var increase = this.data.increase
    this.setData({
      increase: !increase,
      aniStyle: true
    })
  },
  //点击空白隐藏message下选框
  outbtn() {
    this.setData({
      increase: false,
      aniStyle: true
    })
  },
  //发送图片
  chooseImage() {
    var that = this
    that.getOnLine();
    wx.chooseImage({
      count: 9, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: baseUrl + '/chat_api/uploadChat', //服务器地址
          filePath: tempFilePaths[0],
          name: 'file',
          headers: {
            'Content-Type': 'form-data'
          },
          success: function (resp) {
            let json_res = JSON.parse(resp.data)
            console.log('code'+json_res.code);
            if (json_res.code>0){
              if (json_res.data) {
                that.setData({
                  increase: false
                })
                wx.sendSocketMessage({
                  data: JSON.stringify({ message: json_res.data, uid: app.globalData.userInfo.id, tuid: that.data.userId, p_id: that.data.newslist[0].id, type: 2, is_read: 2, length: '' }),
                  success: res => {
                    that.setData({
                      message: ''
                    })


                  }
                });

                // let url = '/chat_api/addInfo';
                // let params = {
                //   uid: app.globalData.userInfo.id,
                //   a_uid: that.data.userId,
                //   message: json_res.data,
                //   p_id: that.data.newslist[0].id,
                //   type: 2,
                //   is_read: 2
                // }
                // app.HttpPostSend(url, params, function (data) {

                //   if (Number(that.data.on_line_uid) != Number(app.globalData.userInfo.id)) {
                //     // 发送模板消息-未读回信提醒
                //     app.sendTemplateMessage(that.data.userId, 3, '/pages/socks/socks?jsid=' + that.data.userId + '&fsid=' + app.globalData.userInfo.id, '', '', '', '')
                //   }
                // });
              }
              
            }else{
              wx.showModal({
                title: '提示',
                content: json_res.data,
                showCancel:false,
                success:function(){}
              })
            }
            
          }
        })
      }
    })
  },
  //图片预览
  previewImg(e) {
    var that = this
    //必须给对应的wxml的image标签设置data-set=“图片路径”，否则接收不到
    var res = e.target.dataset.src
    var list = this.data.previewImgList //页面的图片集合数组
    //判断res在数组中是否存在，不存在则push到数组中, -1表示res不存在
    if (list.indexOf(res) == -1) {
      this.data.previewImgList.push(res)
    }
    wx.previewImage({
      current: res, // 当前显示图片的http链接
      urls: that.data.previewImgList // 需要预览的图片http链接列表
    })
  },

  //切换语音发送
  changeMic: function () {
    this.setData({
      mic_audio: !this.data.mic_audio
    })
  },

  longTap: function () {
    console.log('longTap....')
    var that = this;
    const options = {
      duration: 10000,//指定录音的时长，单位 ms
      sampleRate: 16000,//采样率
      numberOfChannels: 1,//录音通道数
      encodeBitRate: 96000,//编码码率
      format: 'mp3',//音频格式，有效值 aac/mp3
      frameSize: 50,//指定帧大小，单位 KB
    }
    recorderManager.start(options)
    recorderManager.onStart(res => {
      console.log('recorder start')
    })
    that.setData({
      audio_mic: true,
      audio_text: "松开 结束"
    })
  },

  touchcancel: function () {
    var that = this;
    this.setData({
      audio_mic: false,
      audio_text: "按住 说话"
    })
    recorderManager.stop()
    recorderManager.onStop(res => {
      console.log('松开按钮结束:', res)
    })
  },

  //长按说话发送
  recordStart: function () {
  },

  //松开按钮结束
  recordEnd: function () {
    var that = this;
    this.setData({
      audio_mic: false,
      audio_text: "按住 说话"
    })
    recorderManager.stop()
    recorderManager.onStop(res => {
      console.log('松开按钮结束:', res)
      if (getTimeSeconds(res.duration) > 0) {
        //松开上传资源到阿里云oss
        wx.uploadFile({
          url: baseUrl + '/chat_api/uploadChat', //服务器地址
          filePath: res.tempFilePath, //音频地址
          name: 'file',
          headers: {
            'Content-Type': 'form-data'
          },
          success: function (resp) {
            let json_res = JSON.parse(resp.data);
            console.log(json_res, "上传成功时候返回得地址");
            that.submitAudio(json_res.data, getTimeSeconds(res.duration));
            that.setData({
              audio_mic: false
            })
          },
        });
        //上传结束
      }
    })
  },

  //发送语音信息
  submitAudio: function (audioUrl, len) {
    var that = this;
    // that.getOnLine();
    wx.sendSocketMessage({
      data: JSON.stringify({ message: audioUrl, uid: app.globalData.userInfo.id, tuid: that.data.userId, p_id: that.data.newslist[0].id, type: 3, is_read: 2, length: len}),
      success: res => {
        that.setData({
          message: ''
        })


      }
    });

    // that.getOnLine();
    // let url = '/chat_api/addInfo';
    // let params = {
    //   uid: app.globalData.userInfo.id,
    //   a_uid: that.data.userId,
    //   message: audioUrl,
    //   p_id: that.data.newslist[0].id,
    //   type: 3,
    //   is_read: 2,
    //   length: len
    // }
    // app.HttpPostSend(url, params, function (data) {

    //   if (Number(that.data.on_line_uid) != Number(app.globalData.userInfo.id)) {
    //     // 发送模板消息-未读回信提醒
    //     app.sendTemplateMessage(that.data.userId, 3, '/pages/socks/socks?jsid=' + that.data.userId + '&fsid=' + app.globalData.userInfo.id, '', '', '', '')
    //   }

    // });
  },

  audioPlay: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var theAudio = that.data.newslist;
    var file = e.currentTarget.dataset.audio;
    for (var i = 0; i < theAudio.length; i++) {
      theAudio[i].isaudio = true;
      theAudio[i].noPlay = true;
    }
    theAudio[index].isaudio = false;
    theAudio[index].noPlay = false;

    wx.setInnerAudioOption({
      obeyMuteSwitch: false,
      success: function (e) {
        console.log(e)
        console.log('play success')
      },
      fail: function (e) {
        console.log(e)
        console.log('play fail')
      }
    })

    innerAudioContext.src = file
    innerAudioContext.obeyMuteSwitch = false
    innerAudioContext.play()
    innerAudioContext.onPlay(res => {
      console.log('recorder play start')
    })

    innerAudioContext.onEnded(res => {
      console.log('recorder onEnded start')
      theAudio[index].isaudio = true;
      theAudio[index].noPlay = true;
    })

    that.setData({
      newslist: theAudio
    })
  },

  // 结束播放录音
  audioStopPlay: function (e) {
    const that = this
    var index = e.currentTarget.dataset.index;
    var theAudio = that.data.newslist;
    var file = e.currentTarget.dataset.audio;
    theAudio[index].isaudio = true;
    theAudio[index].noPlay = true;


    innerAudioContext.src = file
    innerAudioContext.stop()
    innerAudioContext.onStop(res => {
      console.log('tap stop')
    })
    that.setData({
      newslist: theAudio
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    var that = this;
    that.data.sk.close();
    wx.onSocketClose(function () {
      console.log('Socket关闭');
      clearInterval(that.data.setInter);

      let url2 = '/user_api/onLine';
      let params2 = {
        uid: app.globalData.userInfo.id,
        on_line_uid: 0
      }
      app.HttpPostSend(url2, params2, function (res) {

      });
    });
    
  },

})